//配置路由的地方
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
//使用插件
Vue.use(VueRouter)
//引入路由组件
// import routes from './routes'
let originPush = VueRouter.prototype.push
let originreplace = VueRouter.prototype.replace
//重写push|replace
//第一个参数：告诉原来push方法，你往哪里跳转（传递那些参数）
//call||apply区别
//相同点：都可以调用函数一次，都可以篡改函数的上下文一次
//不同点：call和apply传递参数，call传递参数用，隔开 apply方法执行传数组
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originreplace.call(this, location, resolve, reject)
  } else {
    originreplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
// 静态路由
const staticRouting = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/layout',
    name: 'layout',
    redirect: '/home',
    component: () => import('@/layout/index.vue'),
    children: []
  },
  {
    path: '*',
    name: '404',
    component: () => import('@/views/error/404.vue')
  }
]

let router = new VueRouter({
  mode: 'hash',
  //配置路由
  routes: staticRouting,
  //滚动行为
  scrollBehavior() {
    return { y: 100 }
  }
})
// const path = '/home/index'
// const ll = {
//   path: '/home',
//   name: 'home',
//   component: () => import(`@/views/${path}.vue`),
//   meta: {
//     title: '首页',
//     icon: 'el-icon-s-home',
//     isFull: false
//   }
// }
// 路由前置守卫
router.beforeEach((to, from, next) => {
  const isHasRoute = store.state.menu.menuList?.length
  if (!isHasRoute) {
    store.dispatch('getMenuListApi')
    initRoutes()
    return next({ ...to, replace: true })
  }
  next()
})

//初始化路由
const initRoutes = () => {
  const menusList = store.getters.flatMenuListGet
  menusList.forEach(item => {
    item.children && delete item.children
    if (item.component && typeof item.component == 'string') {
      const path = item.component
      item.component = () => import(`@/views/${path}.vue`)
    }
    if (item.meta.isFull) {
      router.addRoute(item)
    } else {
      router.addRoute('layout', item)
    }
  })
}

export default router
